package com.hengxinguotong.zhihuichengjian.ui;

import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.Handler;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;

import com.hengxinguotong.zhihuichengjian.R;
import com.hengxinguotong.zhihuichengjian.bean.SettingsItem;
import com.hengxinguotong.zhihuichengjian.dialog.AppUpgradeDialog;
import com.hengxinguotong.zhihuichengjian.utils.CacheManager;
import com.hengxinguotong.zhihuichengjian.utils.SPUtil;
import com.hengxinguotong.zhihuichengjian.utils.Utils;
import com.hengxinguotong.zhihuichengjian.widget.font.HXTextView;
import com.hengxinguotong.zhihuichengjian.widget.view.CustomPatient;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.OnItemClick;
import butterknife.Unbinder;
import cn.jpush.android.api.JPushInterface;

/**
 * Created by Administrator on 2017/6/20.
 */

public class SettingsActivity extends BaseActivity implements View.OnClickListener,AdapterView.OnItemClickListener{

    @BindView(R.id.tv_logout)
    HXTextView tv_logout;
    @BindView(R.id.setting_list)
    ListView setting_list;
    @BindView(R.id.title_tv)
    HXTextView title_tv;
    @BindView(R.id.iv_back)
    HXTextView iv_back;
    Unbinder unbinder;

    private SettingsActivity mActivity;
    private SettingAdapter adapter;
    private List<SettingsItem> list;
    private boolean hasNewVersion;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_settings);
        unbinder = ButterKnife.bind(this);
        mActivity = this;
        initList();
    }

    private void initList(){
        list = new ArrayList<>();
        SettingsItem item = new SettingsItem(R.mipmap.huancun, "清除缓存", CacheManager.getUsedPercentValue(this), false);
        list.add(item);
        item = new SettingsItem(R.mipmap.mima, "修改密码", "", false);
        list.add(item);
        item = new SettingsItem(R.mipmap.fankui, "意见反馈", "", false);
        list.add(item);
        String versionName = Utils.getVersionName(mActivity);
        SharedPreferences sp = SPUtil.getSharedPreferece(mActivity);
        hasNewVersion = sp.getBoolean("hasNewVersion", false);
        item = new SettingsItem(R.mipmap.gengxin, "检查更新", "V" + versionName, hasNewVersion);
        list.add(item);
        item = new SettingsItem(R.mipmap.shezhe_xuanfukuang, "悬浮窗", "", false);
        list.add(item);
        //不显示关于我们
//        item = new SettingsItem(R.mipmap.guanyu, "关于我们", "", false);
//        list.add(item);
        adapter = new SettingAdapter(list);
        setting_list.setAdapter(adapter);
    }

    @OnClick({R.id.tv_logout, R.id.iv_back})
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.tv_logout:
                new Handler().post(new Runnable() {
                    @Override
                    public void run() {
                        showLoginoutDialog();
                    }
                });
                break;

            case R.id.iv_back:
                finish();
                break;
        }
    }

    private double x = 0;
    @OnItemClick({R.id.setting_list})
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

        Intent intent;
        switch (position){
            case 0:
//                Toast.makeText(mActivity, "功能开发中，敬请期待…", Toast.LENGTH_LONG ).show();
                CacheManager.clearMem(this);
//                CleanManager.cleanApplicationData(this);
                if(x == 0){
                    x = Math.random();
                }else{
                    double y = Math.random();
                    if(y < x){
                        x = y;
                    }
                }

                DecimalFormat df=new java.text.DecimalFormat("#.##");
//                list.get(0).setItem_content(df.format(x) + "M");
                list.get(0).setItem_content( "0M");
                adapter.notifyDataSetChanged();
                break;
            case 1:
                intent = new Intent(mActivity, ModifyActivity.class);
                startActivity(intent);
                break;
            case 2:
                intent = new Intent(mActivity, FeedBackActivity.class);
                startActivity(intent);
                break;
            case 3:
//                Toast.makeText(mActivity, "功能开发中，敬请期待…", Toast.LENGTH_LONG ).show();
                if(hasNewVersion){
                    new Handler().post(new Runnable() {
                        @Override
                        public void run() {
                            showUpdateDialog();
                        }
                    });
                }else{
                    showToast("当前已是最新版");
                }
                break;
            case 4:
                int level = SPUtil.getInt(mActivity, "level");
                if(level == 3){
                    showToast("当前角色没有此功能");
                }else{
                    intent = new Intent(mActivity, FloatSwitchActivity.class);
                    startActivity(intent);
                }
                break;
                //不显示关于我们
//            case 5:
//                intent = new Intent(mActivity, WebViewActivity.class);
//                intent.putExtra("url", "file:///android_asset/about.html");
//                intent.putExtra("title", "关于我们");
//                startActivity(intent);
//                break;
        }
    }

    private void showUpdateDialog(){
        final String filePath = SPUtil.getString(mActivity, "apkPath");
        //提醒更新
        CustomPatient.Builder builder = new CustomPatient.Builder(mActivity);
        Typeface lantypeFace = Utils.getTypeface(mActivity);
        Typeface typeFace = Utils.getTypeface(mActivity);
        builder.setTitle("版本更新");
        builder.setContent("检测到新版本，立即更新吗？", lantypeFace, typeFace);
        builder.setPositiveButton("稍后更新", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();

            }
        });

        builder.setNegativeButton("立即更新",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
//                        Utils.downFile(filePath, SettingsActivity.this);
                        AppUpgradeDialog appUpgradeDialog = new AppUpgradeDialog(SettingsActivity.this);
                        appUpgradeDialog.setDownloadPath(filePath);
                        appUpgradeDialog.show();
                    }
                });
        CustomPatient CustomPatient = builder.create();
        CustomPatient.show();
        Window window = CustomPatient.getWindow() ;
        WindowManager m = getWindowManager();
        Display d = m.getDefaultDisplay(); // 获取屏幕宽、高用
        WindowManager.LayoutParams p = window.getAttributes(); // 获取对话框当前的参数值
        p.height = (int) (d.getHeight() * 0.23); // 改变的是dialog框在屏幕中的位置而不是大小
        p.width = (int) (d.getWidth() * 0.85); // 宽度设置为屏幕的0.65
        window.setAttributes(p);
    }

    //提示退出登录对话框
    private void showLoginoutDialog() {
        Typeface lantypeFace = Utils.getTypeface(mActivity);
        Typeface typeFace = Utils.getTypeface(mActivity);
        CustomPatient.Builder builder = new CustomPatient.Builder(mActivity);
        builder.setContent("退出登录", lantypeFace, typeFace);
        builder.setPositiveButton("取消", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        builder.setNegativeButton("确定",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        //设置你的操作事项
                        if(FloatSwitchActivity.floatService != null){
                            stopService(FloatSwitchActivity.floatService);
                            FloatSwitchActivity.floatService = null;
                            SPUtil.put(mActivity, "service", 0);
                        }
//                        Intent intent = new Intent(mActivity, FloatWindowService.class);
//                        stopService(intent);
//                        SPUtil.put(mActivity, "service", 0);
                        Utils.loginOut(mActivity);
                    }
                });

        CustomPatient CustomPatient = builder.create();
        CustomPatient.show();
        Window window = CustomPatient.getWindow();
        WindowManager m = getWindowManager();
        Display d = m.getDefaultDisplay(); // 获取屏幕宽、高用
        WindowManager.LayoutParams p = window.getAttributes(); // 获取对话框当前的参数值
        p.height = (int) (d.getHeight() * 0.20); // 宽度设置为屏幕的0.20
        p.width = (int) (d.getWidth() * 0.70); // 宽度设置为屏幕的0.65
        window.setAttributes(p);
    }

    public class SettingAdapter extends BaseAdapter{

        private List<SettingsItem> list;

        public SettingAdapter(List<SettingsItem> list) {
            this.list = list;
        }

        @Override
        public int getCount() {
            return list.size();
        }

        @Override
        public Object getItem(int position) {
            return list.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder = null;
            if(null == convertView || null == convertView.getTag()){
                holder = new ViewHolder();
                convertView = LayoutInflater.from(mActivity).inflate(R.layout.item_settings, null);
                holder.item_icon = (ImageView) convertView.findViewById(R.id.item_icon);
                holder.item_name = (HXTextView)convertView.findViewById(R.id.item_name);
                holder.item_content = (HXTextView)convertView.findViewById(R.id.item_content);
                holder.new_version = (HXTextView)convertView.findViewById(R.id.new_version);
                convertView.setTag(holder);
            }else{
                holder = (ViewHolder) convertView.getTag();
            }
            SettingsItem item = list.get(position);
            holder.item_icon.setImageResource(item.getItem_icon());
            holder.item_name.setText(item.getItem_name());
            holder.item_content.setText(item.getItem_content());
            if(item.isNew()){
                holder.new_version.setVisibility(View.VISIBLE);
            }else{
                holder.new_version.setVisibility(View.INVISIBLE);
            }
            return convertView;
        }

        private class ViewHolder {
            ImageView item_icon;
            HXTextView item_name, item_content, new_version;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        JPushInterface.onResume(getApplicationContext());
    }
    @Override
    protected void onPause() {
        super.onPause();
        JPushInterface.onPause(getApplicationContext());
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        unbinder.unbind();
    }
}
